package com.qianji.petmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianji.common.exception.NoStockException;
import com.qianji.common.exception.RabbitEnum;
import com.qianji.common.to.MemberResponseVo;
import com.qianji.common.to.mq.OrderTo;
import com.qianji.common.to.seckill.SeckillCartTo;
import com.qianji.common.utils.PageUtils;
import com.qianji.common.utils.Query;
import com.qianji.common.utils.R;
import com.qianji.petmall.order.config.AlipayTemplate;
import com.qianji.petmall.order.constants.OrderConstants;
import com.qianji.petmall.order.dao.OrderDao;
import com.qianji.petmall.order.entity.OrderEntity;
import com.qianji.petmall.order.entity.OrderItemEntity;
import com.qianji.petmall.order.entity.PaymentInfoEntity;
import com.qianji.petmall.order.enume.OrderStatusEnum;
import com.qianji.petmall.order.feign.CartFeignService;
import com.qianji.petmall.order.feign.MemberFeignService;
import com.qianji.petmall.order.feign.ProductFeignService;
import com.qianji.petmall.order.feign.WareFeignService;
import com.qianji.petmall.order.interceport.LoginUserInterceptor;
import com.qianji.petmall.order.service.OrderItemService;
import com.qianji.petmall.order.service.OrderService;
import com.qianji.petmall.order.service.PaymentInfoService;
import com.qianji.petmall.order.to.OrderCreateTo;
import com.qianji.petmall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVO> configMemberAddress = new ThreadLocal<>();

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public void CreatSeckillCart(SeckillCartTo cart) {
        //保存订单信息
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(cart.getOrderSn());
        entity.setMemberId(cart.getMemberId());
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = cart.getPayAmount().multiply(new BigDecimal(cart.getNum()));
        entity.setPayAmount(multiply);
        this.save(entity);

        //保存订单项信息
        OrderItemEntity item = new OrderItemEntity();
        item.setOrderSn(cart.getOrderSn());
        item.setRealAmount(multiply);
        item.setSkuQuantity(cart.getNum());
        orderItemService.save(item);

    }

    @Override
    public boolean aliAsyncNotify(PayAsyncVo payAsyncVo, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息 验签
        boolean b = ifPayAsync(request);
        if (b){
            System.out.println("验签成功");
            //需要将支付宝的流水保存到数据库oms_payment_info中
            PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
            paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
            paymentInfoEntity.setCreateTime(payAsyncVo.getNotify_time());
            paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
            paymentInfoEntity.setTotalAmount(payAsyncVo.getTotal_amount());

            paymentInfoService.save(paymentInfoEntity);

            //TODO 修改订单的状态
            //获取到支付宝交易是否完成状态 TRADE_SUCCESS  TRADE_FINISHED  以上两种状态都是完成支付
            String status = payAsyncVo.getTrade_status();
            if (status.equals("TRADE_SUCCESS")||status.equals("TRADE_FINISHED")){
                LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
                LambdaUpdateWrapper<OrderEntity> eq = wrapper.set(OrderEntity::getStatus, OrderStatusEnum.PAYED.getCode()).eq(OrderEntity::getOrderSn, payAsyncVo.getOut_trade_no());
                this.update(eq);
            }
        }
        return b;

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
    }

    private boolean ifPayAsync(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSign_type()); //调用SDK验证签名
        if (signVerified){
            System.out.println("验签成功");
        }else {
            System.out.println("支付宝验签失败");
        }
        return signVerified;
    }

    @Override
    public PageUtils getListOrderItem(Map<String, Object> map) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.thread_Local.get();
        Long id = memberResponseVo.getId();
        IPage<List<OrderEntity>> listIPage = this.baseMapper.selectUserItem(new Query<OrderEntity>().getPage(map), id);

        return new PageUtils(listIPage);
    }

    @Override
    public PayVo payOrder(String orderSn) {
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        OrderEntity orderItemStatus = this.getOrderItemStatus(orderSn);
        //保留两位小数点，向上取值
        BigDecimal bigDecimal = orderItemStatus.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        //查询订单项的数据
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity item = order_sn.get(0);
        payVo.setSubject(item.getSkuName());
        payVo.setBody(item.getSkuAttrsVals());
        return payVo;
    }

    /**
     * 关闭订单超时业务
     * @param order
     */
    @Override
    public void closeOrder(OrderEntity order) {
        //关闭订单前先查询订单是否是已支付
        OrderEntity entity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", order.getOrderSn()));
        if (entity.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
            //待付款状态进行关闭订单
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setId(order.getId());
            log.info("订单未支付，修改订单状态");
            orderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.baseMapper.updateById(orderEntity);
        }
        //关闭订单后再发一条消息给mq
        log.info("订单关闭后再次发送给队列确认库存是否关闭");
        OrderTo orderTo = new OrderTo();
        BeanUtils.copyProperties(order,orderTo);
        if (!entity.getStatus().equals(OrderStatusEnum.PAYED.getCode())){
            try {
                //TODO 保证消息一点会发出去
                rabbitTemplate.convertAndSend(RabbitEnum.ORDER_EXCHANGE_RABBIT.getMq(),RabbitEnum.ORDER_RELEASE_OTHER.getMq(),orderTo);
            }catch (Exception e){
                //TODO 将设法发送成功的消息进行重试
            }
        }

    }

    @Override
    public OrderEntity getOrderItemStatus(String orderSn) {
        OrderEntity order = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order;
    }

    //TODO 是本地事务，在分布式的系统下只能控制自己服务的回滚，而不能让其它服务回滚   分布式事务的最大原因：网络问题
    @Transactional
    @Override
    public OrderResponseVo submitOrder(OrderSubmitVO submitVO) throws ExecutionException, InterruptedException {
        OrderResponseVo orderResponseVo = new OrderResponseVo();
        //令牌的对比和删除必须是原子性
        MemberResponseVo memberResponseVo = LoginUserInterceptor.thread_Local.get();
        orderResponseVo.setCode(200);
        String userId = redisTemplate.opsForValue().get(OrderConstants.USER_ORDER_TOKEN+memberResponseVo.getId());
        String orderToken = submitVO.getOrderToken();
        if (orderToken!=null && orderToken.equals(userId)){
            //删除redis中的order:token
            Boolean extracted = extracted(memberResponseVo);
            if (extracted == false){
                //令牌检验失败
                orderResponseVo.setCode(1);
                return orderResponseVo;
            }
            configMemberAddress.set(submitVO);
            //TODO 1、创建订单项等消息
            OrderCreateTo create = orderCreate();
            //TODO 2、验证价格
            BigDecimal payAmount = create.getOrder().getPayAmount();
            BigDecimal payPrice = submitVO.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比成功
                //TODO 3、保存订单
                saveOrder(create);
                //TODO 4、库存锁定，只要有异常就回滚数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(create.getOrder().getOrderSn());
                List<OrderItemEntity> orderItem = create.getOrderItem();
                List<OrderItemVo> collect = orderItem.stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                //TODO 远程锁库存
                R r = wareFeignService.orderLock(wareSkuLockVo);
                if (r.getCode()==0){
                    //TODO 锁定成功
                    orderResponseVo.setOrder(create.getOrder());
                    //TODO 远程扣减积分
                    /**
                     * TODO 如果使用我们的异常机制回滚数据会导致：
                     * 1、当远程服务出现假失败，order保存订单服务会回滚数据，而远程的库存服务感知不到，不会回滚数据，会继续锁定库存
                     * 假失败：远程服务没有问题，但是我们调用远程服务的时候可能由于网络的原因导致没能调用成功，就导致了远程服务减了库存而保存订单服务回滚了订单
                     *         出现减库存没订单
                     * 2、当远程服务执行成功了，但是其它服务执行失败了也会导致回滚，而远程服务没回滚
                     */
                    //TODO 给rabbitmq发送消息
                    rabbitTemplate.convertAndSend(RabbitEnum.ORDER_EXCHANGE_RABBIT.getMq(),
                            RabbitEnum.ORDER_CREATE_ORDER.getMq(),
                            create.getOrder());
                    return orderResponseVo;
                }else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    orderResponseVo.setCode(3);
                    //使用异常机制回滚数据
                    throw new NoStockException(msg);
                }
            }else {
                //金额对比失败
                orderResponseVo.setCode(2);
                return orderResponseVo;
            }
        }else {
            orderResponseVo.setCode(1);
            return orderResponseVo;
        }
    }

    /**
     * 保存订单的所有数据
     * @param create
     */
    private void saveOrder(OrderCreateTo create) {
        //获取订单信息
        OrderEntity order = create.getOrder();
        //订单创建和修改时间
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItem = create.getOrderItem();
        //批量保存订单项
        orderItemService.saveBatch(orderItem);
    }

    /**
     * 删除令牌
     * @param memberResponseVo
     * @return
     */
    private Boolean extracted(MemberResponseVo memberResponseVo) {
        //用户的防重令牌和redis中保存的一致
        RLock lock = redissonClient.getLock("Lock");
        //加锁
        lock.lock();
        Boolean delete;
        try {
            //删除redis中的order:token
            delete = redisTemplate.delete(OrderConstants.USER_ORDER_TOKEN + memberResponseVo.getId());
        }finally {
            //释放锁
            lock.unlock();
        }
        return delete;
    }
    //TODO 创建订单
    public OrderCreateTo orderCreate() throws ExecutionException, InterruptedException {
        OrderCreateTo create = new OrderCreateTo();
        //1、生成订单号

        String orderSn = IdWorker.getTimeId();
        // 构建订单数据【封装价格】
        OrderEntity orderEntity = orderAddr(orderSn);
        //2、获取到所有的订单项【封装价格】
        List<OrderItemEntity> orderItem = builderOrder(orderSn);
        //3、验价(计算价格、积分等信息)
        computPrice(orderEntity, orderItem);

        create.setOrderItem(orderItem);
        create.setOrder(orderEntity);
        return create;
    }

    private void computPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItem) {
        //优惠后的总价
        BigDecimal realAmount = new BigDecimal("0");
        //优惠价
        BigDecimal couponAmount = new BigDecimal("0");
        BigDecimal integrationAmount =new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        //积分、成长值
        Integer giftIntegration = 0;
        Integer giftGrowth = 0;
        for (OrderItemEntity item : orderItem) {
            giftGrowth += item.getGiftGrowth();
            giftIntegration += item.getGiftIntegration();
            realAmount = realAmount.add(item.getRealAmount());
            couponAmount = couponAmount.add(item.getCouponAmount());
            integrationAmount = integrationAmount.add(item.getIntegrationAmount());
            promotionAmount = promotionAmount.add(item.getPromotionAmount());
        }
        //总价
        orderEntity.setTotalAmount(realAmount);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(realAmount.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(couponAmount);
        orderEntity.setPromotionAmount(promotionAmount);
        orderEntity.setIntegrationAmount(integrationAmount);
        //设置积分成长值信息
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
        //设置删除的状态
        orderEntity.setDeleteStatus(0);
    }

    private List<OrderItemEntity> builderOrder(String orderSn) throws ExecutionException, InterruptedException {
        List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
        if (currentCartItems!=null && currentCartItems.size()>0){
            List<OrderItemEntity> collect = currentCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = orderItems(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    private OrderItemEntity orderItems(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //商品的spu信息
        Long skuId = item.getSkuId();
        R skuInfoBySpuId = productFeignService.getSkuInfoBySpuId(skuId);
        SpuInfoVo spuItem = skuInfoBySpuId.getData(new TypeReference<SpuInfoVo>() {});

        orderItemEntity.setCategoryId(spuItem.getCatalogId());
        orderItemEntity.setSpuId(spuItem.getId());
        orderItemEntity.setSpuName(spuItem.getSpuName());
        orderItemEntity.setSpuBrand(spuItem.getBrandId().toString());
        //商品的sku信息
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        String attr = StringUtils.collectionToDelimitedString(item.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(attr);
        orderItemEntity.setSkuQuantity(item.getCount());
        //积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        //订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        BigDecimal multiply = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        orderItemEntity.setRealAmount(multiply
                        .subtract(orderItemEntity.getPromotionAmount())
                        .subtract(orderItemEntity.getCouponAmount())
                        .subtract(orderItemEntity.getIntegrationAmount()));
        return orderItemEntity;
    }

    private OrderEntity orderAddr(String orderSn) {
        OrderSubmitVO vo = configMemberAddress.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        //TODO 远程调用查询用户地址信息
        R fare = wareFeignService.getFare(vo.getAddrId());
        FareVo fareData = fare.getData(new TypeReference<FareVo>() {
        });
        //设置收货人信息
        orderEntity.setBillReceiverPhone(fareData.getAddressVo().getPhone());
        orderEntity.setFreightAmount(fareData.getFare());
        orderEntity.setMemberId(fareData.getAddressVo().getMemberId());
        orderEntity.setMemberUsername(fareData.getAddressVo().getName());
        orderEntity.setPayAmount(vo.getPayPrice());
        orderEntity.setReceiverCity(fareData.getAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareData.getAddressVo().getDetailAddress());
        orderEntity.setReceiverProvince(fareData.getAddressVo().getProvince());
        orderEntity.setReceiverPostCode(fareData.getAddressVo().getPostCode());
        orderEntity.setReceiverRegion(fareData.getAddressVo().getRegion());
        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }

    @Override
    public OrderConfirmVo toTrade() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        //首先获取用户登录的信息，储存在拦截器的ThreadLocal中
        MemberResponseVo member = LoginUserInterceptor.thread_Local.get();
//        System.out.println("主线程...."+Thread.currentThread().getId());

        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        /**
         * 收货地址
         */
        //TODO 远程调用的时候可能会超时导致数据还没查询出来调用下一个服务，使用线程池
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(attributes);
//            System.out.println("member线程...."+Thread.currentThread().getId());
            List<MemberAddressVo> address = memberFeignService.address(member.getId());
            confirmVo.setAddress(address);
        }, executor);
        /**
         * 选中的购物项
         */
        //TODO 远程调用购物车，获取选中的商品 也需要用线程池
        CompletableFuture<Void> itemsFuture = CompletableFuture.runAsync(() -> {
            try {
                RequestContextHolder.setRequestAttributes(attributes);
//                System.out.println("cart线程...."+Thread.currentThread().getId());
                List<OrderItemVo> currentCartItems = cartFeignService.getCurrentCartItems();
                confirmVo.setItemVos(currentCartItems);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, executor);
        /**
         * 查询库存
         */
        itemsFuture.thenAcceptAsync((item) ->{
            List<OrderItemVo> itemVos = confirmVo.getItemVos();
            List<Long> collect = itemVos.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.skuStock(collect);
            List<WareStockVo> data = r.getData(new TypeReference<List<WareStockVo>>() {});
            Map<Long, Boolean> wareStock = data.stream().collect(Collectors.toMap(WareStockVo::getSkuId, WareStockVo::getHasStock));
            confirmVo.setHasStock(wareStock);
        },executor);
        /**
         * 查询用户积分
         */
        //TODO 查询积分信息
        Integer integration = member.getIntegration();
        confirmVo.setIntegration(integration);


        //TODO 防重令牌
        UUID uuid = UUID.randomUUID();
        redisTemplate.opsForValue().set(OrderConstants.USER_ORDER_TOKEN+member.getId(),uuid.toString(),30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(uuid.toString());

        CompletableFuture.allOf(addressFuture, itemsFuture).get();
        return confirmVo;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }



}